package getquestion

import (
	"database/sql"
	"fmt"

	"github.com/gin-gonic/gin"
)

func Sutestlog(r *gin.Engine) {
	var db *sql.DB
	var err error
	var sid, mal, date string = "0", "0", "0"

	db, err = sql.Open("postgres", "port=5432 user=postgres password=15566840887 dbname=mymbri sslmode=disable")
	if err != nil {
		panic(err)
	}

	// 获取全部成绩信息
	r.GET("/tinfo", func(c *gin.Context) {

		str := "SELECT * FROM testlog"
		rows, err := db.Query(str)
		if err != nil {
			panic(err)
		}

		type stu struct {
			Sid  string `json:"sid"`
			Mal  string `json:"mal"`
			Date string `json:"date"`
		}

		students := make([]*stu, 0)
		for rows.Next() {

			err = rows.Scan(&sid, &mal, &date)
			if err != nil {
				panic(err)
			}

			students = append(students, &stu{
				Sid:  sid,
				Mal:  mal,
				Date: date,
			})
		}
		c.JSON(200, gin.H{
			"students": students,
		})
	})
	// 获取搜索
	r.GET("/gettestlog", func(c *gin.Context) {
		xx := c.Query("xx")
		if xx != "" {

			str := "SELECT * FROM testlog where sid='" + xx + "'"
			rows, err := db.Query(str)
			if err != nil {
				panic(err)
			}

			for rows.Next() {

				err = rows.Scan(&sid, &mal, &date)
				if err != nil {
					panic(err)
				}

				c.JSON(200, gin.H{
					"sid":  sid,
					"mal":  mal,
					"date": date,
				})
			}
		}

	})

	// 添加用户
	r.GET("/inserttestlog", func(c *gin.Context) {
		sid = c.Query("sid")
		mal = c.Query("mal")
		date = c.Query("date")
		if err != nil {
			panic(err)
		}
		str := "INSERT INTO testlog(sid,mal,date) VALUES($1,$2,$3)"
		stmt, err := db.Prepare(str)
		if err != nil {
			panic(err)
		}

		res, err := stmt.Exec(sid, mal, date)
		if err != nil {
			panic(err)
		}

		affect, err := res.RowsAffected()
		if err != nil {
			panic(err)
		}

		fmt.Println("rows affect:", affect)
	})

}
